package com.example.server.plugins

import com.example.commons.Ret
import com.example.server.plugins.routing.*
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.http.content.*
import io.ktor.server.plugins.autohead.*
import io.ktor.server.plugins.doublereceive.*
import io.ktor.server.plugins.statuspages.*
import io.ktor.server.resources.*
import io.ktor.server.response.*
import io.ktor.server.routing.*


fun Application.configureRouting() {

    install(Resources) {

    }

    install(DoubleReceive)

    // https://ktor.io/docs/autoheadresponse.html
    install(AutoHeadResponse)

    install(StatusPages) {
        exception<Throwable> { call, cause ->
            if (cause is AuthorizationException) {
                call.respond(HttpStatusCode.Forbidden, Ret<Unit>(code = 403, msg = "$cause", success = false))
            } else {
                call.respond(HttpStatusCode.InternalServerError, Ret<Unit>(code = 500, msg = "$cause", success = false))
            }
        }

        status(HttpStatusCode.NotFound) { call, status ->
            call.respond(status, Ret<Unit>(code = status.value, msg = "Not Found", success = false))
        }
    }

    routing {
        configFileUploadRouting()
        configArticleRouting()
        configTypeRouting()
        configUserRouting()
        configStaticRouting()
        configAppVersionRouting()
        configToolsRouting()

        singlePageApplication {
            applicationRoute = "/vue"
            vue("vue-ui")
        }
    }
}

class AuthorizationException(override val message: String?) : Throwable()